package com.dykj.fireFighting.server.fire.contractNotifyRecord.cron;

import com.dykj.fireFighting.api.base.appNotification.PushModel;
import com.dykj.fireFighting.api.base.push.service.PushService;
import com.dykj.fireFighting.api.fire.contractNotifyRecord.dto.ContractNotifyRecordPushDto;
import com.dykj.fireFighting.api.fire.contractNotifyRecord.entity.ContractNotifyRecord;
import com.dykj.fireFighting.api.fire.contractNotifyRecord.service.IContractNotifyRecordService;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.server.fire.contractNotifyRecord.mapper.ContractNotifyRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.IOUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import sun.nio.ch.IOUtil;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * 〈一句话功能简述〉<br>
 * 〈定时任务配置〉
 *
 * @author admin
 * @create 2020/2/16
 * @since 1.0.0
 */
@Slf4j
@Component
public class ContractTimmerComponent {

    // 保存任务
    private Map<String, ScheduledFuture<?>> futuresMap = new ConcurrentHashMap<String, ScheduledFuture<?>>();
//    @Autowired
//    private ContractNotifyRecordMapper contractNotifyRecordMapper;
    @Autowired
    private PushService pushService;



    // 创建ThreadPoolTaskScheduler线程池
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;


    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(20);
        //threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        //threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
        return threadPoolTaskScheduler;
    }




    /**
     * 添加任务
     *
     * @param s
     */
    public void addTask(ContractNotifyRecordPushDto s) {
        ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(getRunnable(s), getTrigger(s));
        futuresMap.put(s.getId(), future);
    }

    /**
     * 删除/暂停任务
     *
     * @param key
     * @return
     */
    public boolean pauseeTask(String key) {
        ScheduledFuture toBeRemovedFuture = futuresMap.remove(key);
        if (toBeRemovedFuture != null) {
            toBeRemovedFuture.cancel(true);
            // log.info("删除/暂停任务*************>定时任务id={},", key);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 更新任务
     *
     * @param s
     */
    public void updateTask(ContractNotifyRecordPushDto s) {
        ScheduledFuture toBeRemovedFuture = futuresMap.remove(s.getId());
        if (toBeRemovedFuture != null) {
            toBeRemovedFuture.cancel(true);
        }
        addTask(s);
    }

    /**
     * 执行方法
     *
     * @param contractNotifyRecordPushDto
     * @return
     */
    private Runnable getRunnable(ContractNotifyRecordPushDto contractNotifyRecordPushDto) {
        return new Runnable() {
            @Override
            public void run() {
            //    log.info("开始执行定时任务------->定时任务id={},定时任务code={},定时任务cron={},", taskScheduling.getId(), taskScheduling.getCode(), taskScheduling.getReleaseTime());
                //taskSchedulingService.releaseTask(contractNotifyRecord.getId());
                PushModel pushModel=new PushModel();
                try {
                    BeanUtils.copyProperties(pushModel,contractNotifyRecordPushDto);

                }catch (Exception e)
                {
                    e.printStackTrace();
                }


                pushService.pushAlias(pushModel);
                //只执行一次
                pauseeTask(contractNotifyRecordPushDto.getId());
//                if (taskScheduling.getType() == 0) {
//                    //随机任务执行后删除下次任务
//                    pauseeTask(taskScheduling.getId());
//                }
            }
        };
    }

    /**
     * 触发器
     *
     * @param contractNotifyRecord
     * @return
     */
    private Trigger getTrigger(ContractNotifyRecordPushDto contractNotifyRecord) {
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {

                    LocalDateTime localDateTime = DateUtil.asLocalDateTime(contractNotifyRecord.getNoticeTime());
                    ZoneId zone = ZoneId.systemDefault();
                    Instant instant = localDateTime.atZone(zone).toInstant();
                    //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //log.info("添加定时任务+++++++++>定时任务id={},定时任务code={},定时任务执行时间={}", taskScheduling.getId(), taskScheduling.getCode(), sdf.format(Date.from(instant)));
                    return Date.from(instant);
                }


        };
    }
}
